<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { Local } from '../../utils/storage';
import { CloseOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import {feedback} from "@/api/index.ts";

// 定义父组件传递的属性
const props = defineProps({
  showFeedback: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:showFeedback']);

// 响应 props 变化
watch(() => props.showFeedback, (newVal) => {
  console.log('Feedback component: showFeedback prop changed to', newVal);
});

// 定义反馈表单数据
const adviceArea = ref('');
const showTooltip = ref(false);
const isSmallScreen = ref(false);

// 定义评分项
interface RatingItem {
  id: string;
  title: string;
  score: number;
}

const ratingItems = ref<RatingItem[]>([
  { id: 'product', title: 'Product Quality', score: 0 },
  { id: 'delivery', title: 'Delivery Speed', score: 0 },
  { id: 'service', title: 'Customer Service', score: 0 },
  { id: 'trust', title: 'Would you recommend us', score: 0 }
]);

// 定义评分颜色
const colors = ['#f56c6c', '#e6a23c', '#5cb87a'];

// 处理评分变化
const handleRatingChange = (id: string, value: number) => {
  const item = ratingItems.value.find(item => item.id === id);
  if (item) {
    item.score = value;
  }
};

// 检查屏幕尺寸
onMounted(() => {
  checkScreenSize();
  window.addEventListener('resize', checkScreenSize);
});

const checkScreenSize = () => {
  isSmallScreen.value = window.innerWidth < 768;
};

// 文本验证函数
const validateText = (text: string): string => {
  // 只允许中英文字符、数字、常用标点
  const regex = /[^\u4e00-\u9fa5a-zA-Z0-9.,?!;:'"()\s\-]/g;
  return text.replace(regex, '');
};

// 阻止特殊按键
const preventSpecialKeys = (event: KeyboardEvent) => {
  const forbiddenKeys = [';', '`', '~']; // 禁止的特殊字符
  if (forbiddenKeys.includes(event.key)) {
    event.preventDefault();
    message.warning('This character is prohibited');
  }
};

// 粘贴处理
const handlePaste = (event: ClipboardEvent) => {
  if (!event.clipboardData) return;

  const pastedText = event.clipboardData.getData('text') || '';
  const cleaned = validateText(pastedText);

  if (pastedText !== cleaned) {
    message.warning('Illegal characters in the filtered paste');
  }

  event.preventDefault();
  // 使用更现代的方法插入文本
  const selection = window.getSelection();
  if (!selection || !selection.rangeCount) return;

  selection.deleteFromDocument();
  selection.getRangeAt(0).insertNode(document.createTextNode(cleaned));
};

// 处理输入
const handleInput = (e: Event) => {
  if (e.target instanceof HTMLTextAreaElement) {
    adviceArea.value = validateText(e.target.value);
  }
};

// 定义API接口参数类型
interface FeedbackParams {
  user_id: string;
  website: string;
  feedback: string;
  product_rating: number;
  delivery_rating: number;
  trust_recommend_rating: number;
  service_rating: number;
  [key: string]: string | number;
}

// 反馈建议提交处理
const submitFeedback = async () => {
  if (ratingItems.value.some(item => item.score === 0) || !adviceArea.value) {
    showTooltip.value = true;
    setTimeout(() => {
      showTooltip.value = false;
    }, 2000);
    return;
  }

  // 使用映射对象替代多个if-else
  const ratingMap: Record<string, keyof FeedbackParams> = {
    'product': 'product_rating',
    'delivery': 'delivery_rating',
    'service': 'service_rating',
    'trust': 'trust_recommend_rating'
  };

  const paramsData: FeedbackParams = {
    user_id: Local.get('userInfo')?.id || '',
    website: 'https://lannuan.com',
    feedback: adviceArea.value,
    product_rating: 0,
    delivery_rating: 0,
    trust_recommend_rating: 0,
    service_rating: 0
  };

  // 使用forEach和映射简化代码
  ratingItems.value.forEach(({id, score}) => {
    const field = ratingMap[id];
    if (field) paramsData[field] = score;
  });

  try {
    const res = await feedback(paramsData);
    if (res.code === 200) {
      message.success('Thank you for your feedback!');
      adviceArea.value = '';
      ratingItems.value.forEach(item => item.score = 0);
      emit('update:showFeedback', false);
    }
  } catch (error) {
    console.error('Submit feedback failed', error);
    message.error('Submission failed, please try again later');
  }
};

// 关闭反馈窗口
const closeFeedback = () => {
  console.log('Feedback component: closing feedback window');
  emit('update:showFeedback', false);
};
</script>

<template>
  <div class="feedback-wrapper" v-if="showFeedback">
    <div class="feedback-overlay" @click="closeFeedback"></div>
    <div class="feedback">
      <a-row>
        <a-col :span="24" class="close">
          <CloseOutlined class="close-icon" @click="closeFeedback" />
        </a-col>
      </a-row>

      <a-row>
        <a-col :span="24">
          <div class="feedback-title">Please give us any feedback or advice for how we can serve you better.</div>
        </a-col>
      </a-row>

      <a-row>
        <a-col :span="24">
          <a-textarea
            v-model:value="adviceArea"
            :rows="4"
            placeholder="Tell us more..."
            @input="handleInput"
            @paste="handlePaste"
            @keydown="preventSpecialKeys"
          />
        </a-col>
      </a-row>

      <a-row>
        <a-col :span="24">
          <div class="feedback-title" style="margin-top: 20px;">
            Overall, how would you rate your shopping experience on lannuan.net?
          </div>
        </a-col>
      </a-row>

      <div v-for="item in ratingItems" :key="item.id" class="rating-item">
        <div class="rating-label">{{ item.title + ':' }}</div>
        <a-rate v-model:value="item.score" @change="(value: number) => handleRatingChange(item.id, value)" />
      </div>

      <div class="border"></div>
      <div class="feedback-tooltip" v-if="showTooltip">
        Please complete all ratings and provide feedback.
      </div>

      <a-row :gutter="20">
        <a-col :xs="24" :sm="12" :md="6" :offset="isSmallScreen ? 0 : 6">
          <div class="feedback-btn">
            <a-button type="primary" class="submit" @click="submitFeedback">Submit</a-button>
          </div>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<style scoped lang="scss">
.feedback-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.feedback-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1001;
}

.feedback {
  position: relative;
  z-index: 1002;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  max-width: 600px;
  width: 90%;
  margin: 0 auto;

  .close {
    text-align: right;
    margin-bottom: 10px;

    .close-icon {
      font-size: 20px;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        color: #1890ff;
      }
    }
  }

  .feedback-title {
    font-size: 16px;
    margin-bottom: 15px;
    font-weight: 500;
  }

  .rating-item {
    display: flex;
    align-items: center;
    margin-bottom: 15px;

    .rating-label {
      min-width: 180px;
      margin-right: 15px;
    }
  }

  .border {
    height: 1px;
    background: #f0f0f0;
    margin: 20px 0;
  }

  .feedback-tooltip {
    background: #fff8e6;
    color: #faad14;
    padding: 8px 12px;
    border-radius: 4px;
    margin-bottom: 15px;
    font-size: 14px;
  }

  .feedback-btn {
    text-align: center;
    margin-top: 10px;

    .submit {
      width: 100%;
      background: #000;
      border-color: #000;

      &:hover, &:focus {
        background: #333;
        border-color: #333;
      }
    }
  }
}

@media (max-width: 768px) {
  .feedback {
    padding: 15px;

    .rating-item {
      flex-direction: column;
      align-items: flex-start;

      .rating-label {
        margin-bottom: 5px;
      }
    }
  }
}
</style>
